package com.gao.demo02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * A执行完调用B，B执行完调用C，C执行完调用A
 */
public class demo03 {
    public static void main(String[] args) {

        ResourceLock resourceLock = new ResourceLock();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resourceLock.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resourceLock.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                resourceLock.printC();
            }
        }, "C").start();
    }
}

class ResourceLock {
    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    //    1A 2B 3C
    private int num = 1;

    public void printA() {
        lock.lock();
        try {
//            业务，判断 -> 执行 -> 通知
            while (num != 1) {
//                等待
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName() + "===>AAAA");
//            通知,唤醒指定的线程B
            num = 2;
            conditionB.signal();

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
//            业务，判断 -> 执行 -> 通知
            while (num != 2) {
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName() + "===>BBBBBB");
            num = 3;
            conditionC.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
//            业务，判断 -> 执行 -> 通知
            while (num != 3) {
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName() + "==>CCCCC");
            num = 1;
            conditionA.signal();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
